<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller;

use buwang\base\AdminBaseController;
use think\facade\Db;
use think\facade\View;

class Crud extends AdminBaseController
{
    /*protected $middleware = [
        'login' => ['except' => ['create']]
    ];*/

    protected $model = null;//模型实例

    protected function initialize()
    {
        parent::initialize();

        $this->model = new \app\manage\model\CrudDemo();
    }

    public function create()
    {
        $dirs = array_map('basename', glob(base_path() . '*', GLOB_ONLYDIR));
        if ($dirs === false) return $this->error('应用目录不可读');
        $dirs = array_diff($dirs, ['api', 'common', 'home', 'manage']);//去除系统应用,获取扩展应用
        if (empty($dirs)) return $this->error('暂无应用');

        $apps = $dirs;
        $tables = Db::getConnection()->getTables();

        if (request()->isPost()) {
            $app_name = strtolower(request()->post('app/s'));//'bwmall'
            $table_name = request()->post('table/s');//'bw_crud_demo'
            $controller_name_diy = request()->post('controller/s');//'crud/teSt'
            $model_name_diy = request()->post('model/s');//'crud/teSt'

            try {
                $crud = new \buwang\service\Crud();
                $crud->create($app_name, $table_name, $controller_name_diy, $model_name_diy);
            } catch (\Exception $e) {
                return $this->error($e->getMessage());
            }

            return $this->success();
        }

        View::assign('apps', $apps);
        View::assign('tables', $tables);
        return view();
    }
}
